package com.ericsson.enap.modules.procLog.service.impl;

import com.ericsson.common.pojo.FTPInfoVO;
import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.enap.modules.procLog.constant.ProcConstant;
import com.ericsson.enap.modules.procLog.entity.ProcLogCsv;
import com.ericsson.enap.modules.procLog.mapper.ProcLogMapper;
import com.ericsson.enap.modules.procLog.service.ProcLogService;
import com.ericsson.enap.modules.procLog.task.ProcDownLoadTask;
import com.ericsson.enap.modules.procLog.task.ProcLogDealTask;
import com.ericsson.enap.modules.sys.entity.EnipNetelement;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.sys.service.EpcDictService;
import com.mongodb.BasicDBObject;
import com.mongodb.client.model.IndexModel;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @description: procLog功能service实现类
 * @author: wangjingshi
 * @create: 2021-05-06 09:55
 */
@Service
public class ProcLogServiceImpl implements ProcLogService {

    private Logger log = LoggerUtils.Logger(LogFileName.ProcLogJob);

    @Autowired
    private ProcLogMapper procLogMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private EpcDictService epcDictService;

    @Override
    public List<EnipNetelement> downLoadProcTar(String collectorIp,String procPath,String delay) {
        //1.查询当前采集器配置了哪些网元需要进行下载
        log.info("======= bizType:"+7+" ======= collectorIp:"+collectorIp);
        List<EnipNetelement> list = procLogMapper.queryNetelementList(7,collectorIp);
        CountDownLatch latch = new CountDownLatch(list.size());
        //2.多线程处理下载的网元，最后通过线程计数器的方式保证所有网元ProcLog文件下载完成后进行解析
        FTPInfoVO fTPInfoVO;
        for(int i = 0;i<list.size();i++){
            fTPInfoVO = getFtpInfoVO(list, i);
            //     /home/telorb/raw/
            String remotePath = list.get(i).getDownload_path();
            String localPath = procPath + list.get(i).getId() + File.separator;
            log.info("======= remotePath:"+remotePath + "   EDA: " +list.get(i).getName());
            log.info("======= localPath:"+localPath + "   EDA: " +list.get(i).getName());
            ProcDownLoadTask procDownLoadTask = new ProcDownLoadTask(list.get(i).getId(),fTPInfoVO,remotePath,localPath,latch,delay);
            Thread t = new Thread(procDownLoadTask);
            t.start();
        }
        try {
            latch.await();
            log.info("===== All netelements downLoadProcTar files end! =====");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void unzgAndAnalysis(List<EnipNetelement> list,String procPath) {
        String collectionName = "procLog_table";
        if(!mongoTemplate.collectionExists(collectionName)){
            List<IndexModel> indexModelList = new ArrayList<>();
            BasicDBObject index1 = new BasicDBObject();
            index1.put("startTime",-1);
            BasicDBObject index2 = new BasicDBObject();
            index2.put("rootLogId",-1);
            BasicDBObject index3 = new BasicDBObject();
            index3.put("startTime",-1);
            index3.put("instance",-1);
            indexModelList.add(new IndexModel(index1));
            indexModelList.add(new IndexModel(index2));
            //indexModelList.add(new IndexModel(index3));
            mongoTemplate.createCollection(collectionName).createIndexes(indexModelList);
        }
        Integer procLogDays = Integer.valueOf(epcDictService.selectEpcDict(new EpcDict(ProcConstant.ProcLogDays)).getKeyValue());
        String cleanDate = DateUtils.beforNumDay(new Date(), -procLogDays);
        Query query=new Query(Criteria.where("startTime").lte(cleanDate));
        long count = mongoTemplate.remove(query, ProcLogCsv.class,collectionName).getDeletedCount();
        System.out.println("=== cleanDate:"+cleanDate+"=== count:"+count);

        for(int i=0;i<list.size();i++) {
            Long netId = list.get(i).getId();
            String netName = list.get(i).getName();
            //String path = list.get(i).getDownload_path();
            //String localPath = procPath + netId + path.substring(0, path.lastIndexOf("/"));
            String localPath = procPath + netId;
            ProcLogDealTask task = new ProcLogDealTask(list.get(i).getId(),localPath,mongoTemplate,collectionName,netName);
            Thread t = new Thread(task);
            t.start();
        }
    }

    public static FTPInfoVO getFtpInfoVO(List<EnipNetelement> list, int i) {
        FTPInfoVO fTPInfoVO = new FTPInfoVO();
        fTPInfoVO.setHost(list.get(i).getIp4());
        fTPInfoVO.setPort(21);
        fTPInfoVO.setUserName(list.get(i).getUsername());
        fTPInfoVO.setPassword(list.get(i).getPassword());
        fTPInfoVO.setNetElementID(list.get(i).getId());
        return fTPInfoVO;
    }


}
